package com.twu.biblioteca;

import java.io.InputStream;
import java.io.PrintStream;
import java.util.Scanner;

public class BiblioteccaApp {
    private final BookCollection bookCollection;
    private final MovieCollection movieCollection;
    private final UserCollection userCollection;
    private User currentUser;


    public BiblioteccaApp(BookCollection bookCollection, MovieCollection movieCollection, UserCollection userCollection, User currentUser) {
        this.bookCollection = bookCollection;
        this.movieCollection = movieCollection;
        this.userCollection = userCollection;
        this.currentUser = currentUser;
    }

    public void run(PrintStream ps, InputStream is) {
        ps.println("Welcome to biblioteca!");
        Scanner scanner = new Scanner(is).useDelimiter("\n");
        ps.println(MenuList());
        while (scanner.hasNext()) {
            String option = scanner.next();
           ViewState viewState=find(option).execute(ps, scanner, bookCollection, movieCollection, userCollection,currentUser);
           currentUser=viewState.currentUser;
            if (!viewState.keeploop) {
                return;
            }
            ps.println(MenuList());
        }
    }

    public String MenuList() {
        StringBuilder returnString = new StringBuilder();
        for (Menu menu : Menu.values()) {
            if (!menu.id.equals("8") && (!(menu.id.equals("7") && currentUser == null))) {
                returnString.append(menu.toString() + "\n");
            }
        }
        return returnString.toString();
    }


    public Menu find(String option) {
        for (Menu m : Menu.values()) {
            if (m.id.equals(option)) {
                return m;
            }
        }
        return Menu.InvalidOption;
    }

}
